import { login, getCurrentUserInfo } from '@/api/user'
import localCache from '@/utils/auth'

const state = {
  userInfo: {}, // 用户全部信息
  token: localCache.getCache(localCache.TOKEN_KEY) || '', // token
  currentUserDetail: {}, // 当前用户详细信息
  historyInfo: []
}

const mutations = {
  changeUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  changeToken(state, token) {
    state.token = token
    localCache.setCache(localCache.TOKEN_KEY, token)
  },
  changeUserDetail(state, detail) {
    state.currentUserDetail = detail
  },
  removeToken(state) {
    state.token = ''
    localCache.removeCache(localCache.TOKEN_KEY)
  },
  changeHistoryInfo(state, history) {
    if (history) {
      state.historyInfo.push(history)
    }
  }
}

const actions = {
  async login({ commit }, payload) {
    const res = await login(payload)

    // 保存token和用户信息
    commit('changeUserInfo', res.user)
    commit('changeToken', res.jwt)
  },

  // 获取用户信息
  async userInfoAction({ commit }) {
    const res = await getCurrentUserInfo()
    commit('changeUserDetail', res)
  },
  // 退出登录
  logout({ commit }) {
    commit('removeToken')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
